package com.itheima;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

/*
 * 操作索引库 1.增 2.查 3删
 * */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo01IndexOperation {

    //注入高级客户端对象，用来操作es
    @Autowired
    private RestHighLevelClient client;


    /**
     * 目标：创建索引库
     * 1.创建请求对象
     * 设置索引库name
     * 2.客户端发送请求，获取响应对象
     * 3.打印响应对象中的返回结果
     * 4.关闭客户端，释放连接资源
     */
    @Test
    public void createIndex() throws IOException {
        //1.创建请求对象，创建索引的请求
        CreateIndexRequest request = new CreateIndexRequest("heima");
        //2.客户端发送请求，获取响应对象
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        //3.打印响应对象中的返回结果
        //返回index信息
        String index = response.index();
        boolean acknowledged = response.isAcknowledged();

        System.out.println("index:" + index);
        System.out.println("acknowledged:" + acknowledged);

        //4.关闭客户端，释放连接资源
        //client.close();
    }

    /**
     * 查询索引
     * 1.创建请求对象：查看索引库
     *    设置索引库name
     * 2.客户端发送请求，获取响应对象
     * 3.打印响应结果
     * 4.关闭客户端，释放连接资源
     */
    @Test
    public void getIndex() throws IOException {
        //1.创建请求对象：查看索引库
        GetIndexRequest request = new GetIndexRequest("heima");
        //2.客户端发送请求，获取响应对象
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        //3.打印响应结果
        System.out.println("settings: "+response.getSettings());
        System.out.println("mappings: "+response.getMappings());
        //4.关闭客户端，释放连接资源
        //client.close();
    }

    /**
     * 删除索引
     * 1.创建请求对象：删除索引库
     *    设置索引库name
     * 2.客户端发送请求，获取响应对象
     * 3.打印响应结果4.关闭客户端，释放连接资源
     */
    @Test
    public void delete() throws IOException {
        //1.创建请求对象：删除索引库
        DeleteIndexRequest request = new DeleteIndexRequest("heima");
        //2.客户端发送请求，获取响应对象
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        //3.打印响应结果
        System.out.println("acknowledged：："+response.isAcknowledged());
        //4.关闭客户端，释放连接资源
        //client.close();
    }

}
